<?php
class Petition extends CI_Model{
	
	public $id;
	public $user_id;
	public $title;
	public $text;
	public $category_id; //just ID
	public $category; // OBJECT Category
	public $created_time;
	public $user;
	public $votes;
	public $active;
	public $visible;
	public $vote_ratio;
	
	const TRENDING_MIN_VOTES=2;
	const POPULAR_MIN_VOTES=4;
	
	public function submit_petition($title,$category,$text, $active = 1, $visible = 1){
		
		$current_user = get_instance()->session->userdata('current_user');
		

		$errors = $this->submit_ok($current_user,$title,$category,$text);
		if (!is_null($errors)) return $errors;

		$this->insert_petition($current_user, $title,$category,$text);
		return null;
	}

	private function insert_petition($user_id,$title,$category,$text, $active = 1, $visible = 1 ){
			echo 'successfully reached insertion';
			get_instance()->db->query("INSERT INTO petition(id, user_id, title, text, category_id, created_time, active, visible) 
			VALUES ('DEFAULT', ?, ?, ?, ?, NOW(), ?, ?) ",	array($user_id,$title,$text,$category, $active, $visible));

	}

	private function submit_ok($current_user,$title,$category,$text){
		$errors = null;
		if (is_null($current_user) || !$current_user){
			$errors []= 'You must be logged in to submit a petition.';
			return $errors;
		}
		if (empty($title)) {
			$errors[] = 'You must set a petition title.';
		}
		else{
			$duplicate = get_instance()->db->query('SELECT id, title FROM petition WHERE LOWER(title) = LOWER(?)', array($title))->row();
			if ($duplicate) {
				$petitions = get_instance()->config->item('petitions');
				
				$duplicate_id = $duplicate->id;
				$duplicate_title = $duplicate->title;
				$str="A petition titled <a href=$petitions/view/$duplicate_id > $duplicate_title </a> already exists";
				$errors[] = $str;
			
				return $errors;
			}
			
		}
		if (empty($category) || !is_int($category)) {
			var_dump($category);
			$errors[] = 'You must specify a category.';
		}
		if (empty($text)){
			$errors[] = 'You must set a descpription for your petition.';
		}

		if (!is_null($errors)) return $errors;
		else return null;
	}

	public function getPetition($id){
		sanitizeID($id);
		
		$query = get_instance()->db->query('SELECT * FROM petition WHERE id = ? AND visible = 1', array($id));
		$petition = ($query->num_rows()) ? $query->row() : false;
		if (!$query->num_rows()) return $petition;

		$petition = $this->mapArrayToPetition($petition);
		return $petition;
	}
	
	public function getPetitionsList($type, $offset = 0, $limit){
		
		$result = $this->getSQLresults($type, $offset, $limit );
		$list = null;
		foreach($result as $object){
			$list[] = $this->mapArrayToPetition($object);	
		}
		//$list = sortBy($list, vote);
		return $list;
		
	}
	
	public function sortBy($list, $sort = 'created_time'){
		
		if ($sort == 'vote'){
			usort($list, function($a, $b) {
				return - (($a->votes) - ($b->votes));
			});
			return $list;
		}
		
	}
	
	public function getSQLresults($type = 'popular', $offset = 0 , $limit = 99999999){
		  
		$active = true;
				
		$result = null;
		$query = "SELECT * FROM petition WHERE visible = 1 AND active = $active AND id ";
		
		if ($type == 'popular'){
			$query .= "IN (SELECT petition_id FROM petition_vote GROUP BY petition_id HAVING COUNT(*)";
			$query .= ">= ?) LIMIT ? OFFSET ?";
			$parameters = array(Petition::POPULAR_MIN_VOTES, $limit, $offset);
		}
		else if ($type == 'trending'){
			$query .= "IN (SELECT petition_id FROM petition_vote GROUP BY petition_id HAVING COUNT(*)";
			$query .= ">= ? AND COUNT(*) < ?) LIMIT ? OFFSET ? ";
			$parameters = array(Petition::TRENDING_MIN_VOTES,Petition::POPULAR_MIN_VOTES,$limit,  $offset );
		}
		else if ($type == 'fresh'){
			$query .= "NOT IN (SELECT petition_id FROM petition_vote GROUP BY petition_id HAVING COUNT(*)";
			$query .= ">= ?) LIMIT ? OFFSET ?";
			$parameters = array(Petition::TRENDING_MIN_VOTES, $limit, $offset);
		}
		
		$result = get_instance()->db->query($query, $parameters)->result();

		return $result;
	}
	
	public function mapArrayToPetition($object){
			$vars = get_object_vars($object);
			$new_post = new Petition();
			foreach($vars as $key => $value){
				$new_post->$key = $value;
			}
			$new_post->created_time = strtotime($new_post->created_time);
			
			 get_instance()->load->model('petitions/Category');
			$new_post->category = $this->Category->getCategoryById($new_post->category_id);
			
			get_instance()->load->model('users/User');
			$new_post->user = $this->User->getUserByID($new_post->user_id);

			$new_post->votes = $new_post->getVotes();
			$new_post->vote_ratio = $new_post->getVoteRatio();
			return $new_post;
	}
	
	public function getSimilarPetitions($id){
		$current  = $this->getPetition($id);
		$category = $current->category->id;
		$result = get_instance()->db->query('SELECT * FROM petition WHERE category = ? AND id != ?', array($category, $id))->result();
		return $result;
	}
	
	public function getVoteRatio(){
		$time_alive = (time() - $this->created_time )/60/60/24 ;

		try {
			$ratio = $this->votes / $time_alive;
		}
		catch (Exception $e){
			$ratio = 0;	
		}
		//echo  date('Y-M-d h:i:s',time())  . "  ". date('Y-M-d h:i:s',$this->created_time)  . "  ". $ratio;
		//echo  $time_alive . "  ". $ratio;
		//echo   "<br/>";
		return $ratio;
	}
	
	public function getVotes(){
		$result = get_instance()->db->query("SELECT COUNT(*) as votes FROM petition_vote WHERE petition_id = ?", array($this->id))->row();
		$result = isset($result->votes) ? $result->votes : 0;
		return $result;
	}
}